package com.myqf2.d10_dbutils_xml.dbutils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

//由实现类 来处理结果集
public class dbutils框架使用 {

    static QueryRunner queryRunner = new QueryRunner();
    static Connection con = druid连接池获取连接.getConnection();

    public static void main(String[] args) throws Exception {
//        testArrayHandler();
//        testArrayListHandler();
//        testColumnListHandler();
//        testScalarHandler();
//        testBeanHandler();
        testBeanListHandler();
    }

    // 查询到的第一行数据 放入数组
    static void testArrayHandler() throws SQLException {
        String sql = "select * from user";
        Object[] query = queryRunner.query(con, sql, new ArrayHandler());
        for (Object o : query) {
            System.out.println(o);
        }
    }

    //每一个Object[]就是一行记录
    static void testArrayListHandler() throws SQLException {
        String sql = "select * from user";
        List<Object[]> query = queryRunner.query(con, sql, new ArrayListHandler());
        for (Object[] os : query) {
            for (Object o : os) {
                System.out.print(o + "    ");
            }
            System.out.println();
        }
    }

    //取某一列的数据。封装到List中。
    public static void testColumnListHandler() throws SQLException {
        String sql = "select * from user";
        List<Object> address = queryRunner.query(con, sql, new ColumnListHandler<Object>("address"));
        for (Object o : address) {
            System.out.println(o);
        }
    }

    //行数
    public static void testScalarHandler() throws SQLException {
        String sql = "select count(*) from user";
        //new ScalarHandler<T>():T:表示得到结果的类型
        Long query = queryRunner.query(con, sql, new ScalarHandler<Long>());
        System.out.println(query);
    }

    //取其中一行数据 转成对象
    public static void testBeanHandler() throws SQLException {
        String sql = "select * from user where username=?";
        Integer id = 2;
        String username = "gin";
        //public BeanHandler(java.lang.Class<T> type)
        //type:表示要封装的类的类对象
        User query = queryRunner.query(con, sql, new BeanHandler<User>(User.class), username);
        System.out.println(query.toString());
    }

    //表中所有数据 都转成list
    public static void testBeanListHandler() throws SQLException {
        String sql = "select * from user";
        List<User> query = queryRunner.query(con, sql, new BeanListHandler<User>(User.class));
        for (User u : query) {
            System.out.println(u.toString());
        }
    }
}
